import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jiang Jining
 * @since 2021/11/28 22:33
 */
public class Solution811 {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new LinkedHashMap<>();
        for (String s : cpdomains) {
            analyseDomain(s, map);
        }
        List<String> result = new ArrayList<>();
        map.forEach((k, v) -> result.add(v + " " + k));
        return result;
    }
    
    private void analyseDomain(String domain, Map<String, Integer> map) {
        String[] domainParts = domain.split(" ");
        String domainPart0 = domainParts[0];
        String domainPart1 = domainParts[1];
        int count = Integer.parseInt(domainPart0);
        String[] parts = domainPart1.split("\\.");
        int length = parts.length;
        String curDomain = "";
        for (int i = length - 1; i >= 0; i--) {
            curDomain = parts[i] + curDomain;
            int countCur = map.getOrDefault(curDomain, 0);
            map.put(curDomain, count + countCur);
            curDomain = "." + curDomain;
        }
    }
    
    public static void main(String[] args) {
        String[] s = new String[]{"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"};
        Solution811 solution811 = new Solution811();
        System.out.println(solution811.subdomainVisits(s));
    }
}
